package com.tranquang.multisite.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;
import com.tranquang.multisite.model.Person;
import com.tranquang.multisite.service.PersonService;

import java.util.List;

public class PersonAction extends ActionSupport implements Preparable {
	private PersonService service;
	private List<Person> persons;
	private Person person;
	private Integer id;
	private String firstName;
	private String lastName;
	private String career;
	private String birthday;

	public PersonAction(PersonService service) {
		this.service = service;
	}

	public String execute() {
		this.persons = service.findAll();
		return Action.SUCCESS;
	}

	public String edit() {
		this.person = service.find(getId());
		return "detail";
	}

	public String save() {
        if (this.person == null) {
            if (getId() != null) {
                this.person = service.find(getId());
            } else {
                this.person = new Person();
            }
        }
        this.person.setFirstName(getFirstName());
		this.person.setLastName(getLastName());
		this.person.setCareer(getCareer());
		this.person.setBirthday(getBirthday());
        this.service.save(person);
        this.person = new Person();
		return execute();
	}

	public String update() {
		return save();
	}

	public String delete() {
		service.remove(id);
		this.persons = service.findAll();
		return "list";
	}

	public List<Person> getPersons() {
		return persons;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public void prepare() throws Exception {
		if (id != null)
			person = service.find(id);
	}

	public Person getPerson() {
		return person;
	}

	public void setPerson(Person person) {
		this.person = person;
	}

	public String getFirstName() {
		return firstName;
	}

	public void setFirstName(String firstName) {
		this.firstName = firstName;
	}

	public String getLastName() {
		return lastName;
	}

	public void setLastName(String lastName) {
		this.lastName = lastName;
	}

	public String getCareer() {
		return career;
	}

	public void setCareer(String career) {
		this.career = career;
	}

	public String getBirthday() {
		return birthday;
	}

	public void setBirthday(String birthday) {
		this.birthday = birthday;
	}
}
